// search.js
const app = getApp();

Page({
  data: {
    keyword: '',
    autoFocus: true,
    showCategories: true,
    showRegions: true,
    currentCategory: 'all',
    currentRegion: 'all',
    sortType: 'default',
    priceOrder: 'asc',
    showFilter: false,
    minPrice: '',
    maxPrice: '',
    selectedDays: '',
    selectedThemes: [],
    searchHistory: [],
    hotKeywords: ['青海湖', '敦煌', '张掖丹霞', '西藏', '新疆', '亲子游', '自驾游', '徒步'],
    categories: [
      { id: 'domestic', name: '国内游' },
      { id: 'outbound', name: '出境游' },
      { id: 'surrounding', name: '周边游' },
      { id: 'customized', name: '定制游' },
      { id: 'theme', name: '主题游' },
      { id: 'family', name: '亲子游' },
      { id: 'outdoor', name: '户外探险' }
    ],
    regions: [
      { id: 'qinghai', name: '青甘' },
      { id: 'xinjiang', name: '新疆' },
      { id: 'yunnan', name: '云南' },
      { id: 'ningxia', name: '宁夏' },
      { id: 'xizang', name: '西藏' },
      { id: 'guizhou', name: '贵州' },
      { id: 'huadong', name: '华东' },
      { id: 'guangxi', name: '广西' },
      { id: 'xian', name: '西安' },
      { id: 'sichuan', name: '四川' },
      { id: 'neimeng', name: '内蒙' },
      { id: 'dongbei', name: '东北' },
      { id: 'guangdong', name: '广东' }
    ],
    dayOptions: [
      { value: '1-3', label: '1-3天' },
      { value: '4-7', label: '4-7天' },
      { value: '8-14', label: '8-14天' },
      { value: '15+', label: '15天以上' }
    ],
    themeOptions: [
      { id: 'nature', name: '自然风光' },
      { id: 'culture', name: '人文历史' },
      { id: 'food', name: '美食之旅' },
      { id: 'photography', name: '摄影之旅' },
      { id: 'luxury', name: '奢华体验' },
      { id: 'budget', name: '经济实惠' },
      { id: 'adventure', name: '探险刺激' },
      { id: 'relax', name: '休闲度假' }
    ],
    products: [],
    totalCount: 0,
    pageSize: 10,
    currentPage: 1,
    hasMore: true,
    isLoading: false
  },

  onLoad: function(options) {
    // 获取搜索历史
    this.getSearchHistory();
    
    // 处理从其他页面传来的参数
    if (options) {
      // 如果有关键词参数
      if (options.keyword) {
        this.setData({
          keyword: options.keyword
        });
        this.onSearch();
      }
      
      // 如果有分类参数
      if (options.categoryId) {
        this.setData({
          currentCategory: options.categoryId
        });
        this.fetchProducts();
      }
      
      // 如果有地区参数
      if (options.regionId) {
        this.setData({
          currentRegion: options.regionId
        });
        this.fetchProducts();
      }
      
      // 如果有主题参数
      if (options.themeId) {
        this.setData({
          selectedThemes: [options.themeId]
        });
        this.fetchProducts();
      }
      
      // 如果有类型参数
      if (options.type) {
        switch(options.type) {
          case 'theme':
            // 处理主题类型
            break;
          case 'family':
            // 处理亲子类型
            this.setData({
              currentCategory: 'family'
            });
            break;
          case 'hot':
            // 处理热门类型
            this.setData({
              sortType: 'sales'
            });
            break;
        }
        this.fetchProducts();
      }
    }
  },

  // 获取搜索历史
  getSearchHistory: function() {
    const history = wx.getStorageSync('searchHistory') || [];
    this.setData({
      searchHistory: history
    });
  },

  // 保存搜索历史
  saveSearchHistory: function(keyword) {
    if (!keyword) return;
    
    let history = wx.getStorageSync('searchHistory') || [];
    
    // 如果已存在，先移除
    history = history.filter(item => item !== keyword);
    
    // 添加到头部
    history.unshift(keyword);
    
    // 最多保存10条
    if (history.length > 10) {
      history = history.slice(0, 10);
    }
    
    wx.setStorageSync('searchHistory', history);
    
    this.setData({
      searchHistory: history
    });
  },

  // 清除搜索历史
  clearHistory: function() {
    wx.showModal({
      title: '提示',
      content: '确定要清除搜索历史吗？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('searchHistory');
          this.setData({
            searchHistory: []
          });
        }
      }
    });
  },

  // 使用历史关键词
  useHistoryKeyword: function(e) {
    const keyword = e.currentTarget.dataset.keyword;
    this.setData({
      keyword: keyword
    });
    this.onSearch();
  },

  // 关键词输入
  onKeywordInput: function(e) {
    this.setData({
      keyword: e.detail.value
    });
  },

  // 清除关键词
  clearKeyword: function() {
    this.setData({
      keyword: '',
      products: []
    });
  },

  // 搜索
  onSearch: function() {
    const keyword = this.data.keyword.trim();
    
    if (keyword) {
      this.saveSearchHistory(keyword);
      
      this.setData({
        currentPage: 1,
        products: [],
        hasMore: true
      });
      
      this.fetchProducts();
    }
  },

  // 选择分类
  selectCategory: function(e) {
    const category = e.currentTarget.dataset.category;
    
    this.setData({
      currentCategory: category,
      currentPage: 1,
      products: [],
      hasMore: true
    });
    
    this.fetchProducts();
  },

  // 选择地区
  selectRegion: function(e) {
    const region = e.currentTarget.dataset.region;
    
    this.setData({
      currentRegion: region,
      currentPage: 1,
      products: [],
      hasMore: true
    });
    
    this.fetchProducts();
  },

  // 选择排序方式
  selectSort: function(e) {
    const type = e.currentTarget.dataset.type;
    let priceOrder = this.data.priceOrder;
    
    if (type === 'price') {
      // 价格排序，切换升降序
      priceOrder = priceOrder === 'asc' ? 'desc' : 'asc';
    }
    
    this.setData({
      sortType: type,
      priceOrder: priceOrder,
      currentPage: 1,
      products: [],
      hasMore: true
    });
    
    this.fetchProducts();
  },

  // 显示筛选面板
  showFilterPanel: function() {
    this.setData({
      showFilter: true
    });
  },

  // 隐藏筛选面板
  hideFilterPanel: function() {
    this.setData({
      showFilter: false
    });
  },

  // 最低价输入
  onMinPriceInput: function(e) {
    this.setData({
      minPrice: e.detail.value
    });
  },

  // 最高价输入
  onMaxPriceInput: function(e) {
    this.setData({
      maxPrice: e.detail.value
    });
  },

  // 选择天数
  selectDays: function(e) {
    const days = e.currentTarget.dataset.days;
    
    // 如果已选中，则取消选中
    if (this.data.selectedDays === days) {
      this.setData({
        selectedDays: ''
      });
    } else {
      this.setData({
        selectedDays: days
      });
    }
  },

  // 切换主题
  toggleTheme: function(e) {
    const theme = e.currentTarget.dataset.theme;
    const selectedThemes = [...this.data.selectedThemes];
    
    const index = selectedThemes.indexOf(theme);
    
    if (index > -1) {
      // 如果已选中，则移除
      selectedThemes.splice(index, 1);
    } else {
      // 如果未选中，则添加
      selectedThemes.push(theme);
    }
    
    this.setData({
      selectedThemes: selectedThemes
    });
  },

  // 重置筛选
  resetFilter: function() {
    this.setData({
      minPrice: '',
      maxPrice: '',
      selectedDays: '',
      selectedThemes: []
    });
  },

  // 确认筛选
  confirmFilter: function() {
    this.hideFilterPanel();
    
    this.setData({
      currentPage: 1,
      products: [],
      hasMore: true
    });
    
    this.fetchProducts();
  },

  // 获取商品列表
  fetchProducts: function() {
    if (this.data.isLoading || !this.data.hasMore) return;
    
    this.setData({
      isLoading: true
    });
    
    // 构建查询参数
    const params = {
      page: this.data.currentPage,
      pageSize: this.data.pageSize,
      keyword: this.data.keyword,
      category: this.data.currentCategory !== 'all' ? this.data.currentCategory : '',
      region: this.data.currentRegion !== 'all' ? this.data.currentRegion : '',
      sortType: this.data.sortType,
      priceOrder: this.data.sortType === 'price' ? this.data.priceOrder : '',
      minPrice: this.data.minPrice,
      maxPrice: this.data.maxPrice,
      days: this.data.selectedDays,
      themes: this.data.selectedThemes
    };
    
    // 实际项目中应该从服务器获取数据
    // 这里使用模拟数据
    setTimeout(() => {
      // 模拟数据
      const mockProducts = [
        {
          id: 201,
          title: '美宿 | 西北寻秋 青甘环线7天6晚',
          regionName: '青甘',
          isHot: true,
          price: 8380,
          salesCount: 256,
          rating: 4.8,
          imageUrl: 'https://picsum.photos/id/1016/200/200'
        },
        {
          id: 202,
          title: '美宿 | 极致装达木 青海5天4晚',
          regionName: '青海',
          isHot: true,
          price: 6580,
          salesCount: 189,
          rating: 4.7,
          imageUrl: 'https://picsum.photos/id/1037/200/200'
        },
        {
          id: 203,
          title: '美宿 | 真容西北 青甘环线7天6晚',
          regionName: '青甘',
          isHot: false,
          price: 9380,
          salesCount: 145,
          rating: 4.9,
          imageUrl: 'https://picsum.photos/id/1041/200/200'
        },
        {
          id: 204,
          title: '美宿 | 蒙古秋末 青海6天5晚',
          regionName: '青海',
          isHot: false,
          price: 8380,
          salesCount: 132,
          rating: 4.6,
          imageUrl: 'https://picsum.photos/id/1019/200/200'
        },
        {
          id: 205,
          title: '轻奢 | 风马遗野 呼伦贝尔4晚5天',
          regionName: '内蒙',
          isHot: true,
          price: 7980,
          salesCount: 210,
          rating: 4.8,
          imageUrl: 'https://picsum.photos/id/1018/200/200'
        }
      ];
      
      // 模拟总数
      const totalCount = 28;
      
      // 模拟是否有更多
      const hasMore = this.data.currentPage * this.data.pageSize < totalCount;
      
      // 更新数据
      this.setData({
        products: [...this.data.products, ...mockProducts],
        totalCount: totalCount,
        hasMore: hasMore,
        isLoading: false,
        currentPage: this.data.currentPage + 1
      });
    }, 1000);
    
    // 实际项目中的云函数调用
    // wx.cloud.callFunction({
    //   name: 'getProducts',
    //   data: params,
    //   success: res => {
    //
// search.js
const app = getApp();

Page({
  data: {
    keyword: '',
    autoFocus: true,
    showCategories: true,
    showRegions: true,
    currentCategory: 'all',
    currentRegion: 'all',
    sortType: 'default',
    priceOrder: 'asc',
    showFilter: false,
    minPrice: '',
    maxPrice: '',
    selectedDays: '',
    selectedThemes: [],
    searchHistory: [],
    hotKeywords: ['青海湖', '敦煌', '张掖丹霞', '西藏', '新疆', '亲子游', '自驾游', '徒步'],
    categories: [
      { id: 'domestic', name: '国内游' },
      { id: 'outbound', name: '出境游' },
      { id: 'surrounding', name: '周边游' },
      { id: 'customized', name: '定制游' },
      { id: 'theme', name: '主题游' },
      { id: 'family', name: '亲子游' },
      { id: 'outdoor', name: '户外探险' }
    ],
    regions: [
      { id: 'qinghai', name: '青甘' },
      { id: 'xinjiang', name: '新疆' },
      { id: 'yunnan', name: '云南' },
      { id: 'ningxia', name: '宁夏' },
      { id: 'xizang', name: '西藏' },
      { id: 'guizhou', name: '贵州' },
      { id: 'huadong', name: '华东' },
      { id: 'guangxi', name: '广西' },
      { id: 'xian', name: '西安' },
      { id: 'sichuan', name: '四川' },
      { id: 'neimeng', name: '内蒙' },
      { id: 'dongbei', name: '东北' },
      { id: 'guangdong', name: '广东' }
    ],
    dayOptions: [
      { value: '1-3', label: '1-3天' },
      { value: '4-7', label: '4-7天' },
      { value: '8-14', label: '8-14天' },
      { value: '15+', label: '15天以上' }
    ],
    themeOptions: [
      { id: 'nature', name: '自然风光' },
      { id: 'culture', name: '人文历史' },
      { id: 'food', name: '美食之旅' },
      { id: 'photography', name: '摄影之旅' },
      { id: 'luxury', name: '奢华体验' },
      { id: 'budget', name: '经济实惠' },
      { id: 'adventure', name: '探险刺激' },
      { id: 'relax', name: '休闲度假' }
    ],
    products: [],
    totalCount: 0,
    pageSize: 10,
    currentPage: 1,
    hasMore: true,
    isLoading: false
  },

  onLoad: function(options) {
    // 获取搜索历史
    this.getSearchHistory();
    
    // 处理从其他页面传来的参数
    if (options) {
      // 如果有关键词参数
      if (options.keyword) {
        this.setData({
          keyword: options.keyword
        });
        this.onSearch();
      }
      
      // 如果有分类参数
      if (options.categoryId) {
        this.setData({
          currentCategory: options.categoryId
        });
        this.fetchProducts();
      }
      
      // 如果有地区参数
      if (options.regionId) {
        this.setData({
          currentRegion: options.regionId
        });
        this.fetchProducts();
      }
      
      // 如果有主题参数
      if (options.themeId) {
        this.setData({
          selectedThemes: [options.themeId]
        });
        this.fetchProducts();
      }
      
      // 如果有类型参数
      if (options.type) {
        switch(options.type) {
          case 'theme':
            // 处理主题类型
            break;
          case 'family':
            // 处理亲子类型
            this.setData({
              currentCategory: 'family'
            });
            break;
          case 'hot':
            // 处理热门类型
            this.setData({
              sortType: 'sales'
            });
            break;
        }
        this.fetchProducts();
      }
    }
  },

  // 获取搜索历史
  getSearchHistory: function() {
    const history = wx.getStorageSync('searchHistory') || [];
    this.setData({
      searchHistory: history
    });
  },

  // 保存搜索历史
  saveSearchHistory: function(keyword) {
    if (!keyword) return;
    
    let history = wx.getStorageSync('searchHistory') || [];
    
    // 如果已存在，先移除
    history = history.filter(item => item !== keyword);
    
    // 添加到头部
    history.unshift(keyword);
    
    // 最多保存10条
    if (history.length > 10) {
      history = history.slice(0, 10);
    }
    
    wx.setStorageSync('searchHistory', history);
    
    this.setData({
      searchHistory: history
    });
  },

  // 清除搜索历史
  clearHistory: function() {
    wx.showModal({
      title: '提示',
      content: '确定要清除搜索历史吗？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('searchHistory');
          this.setData({
            searchHistory: []
          });
        }
      }
    });
  },

  // 使用历史关键词
  useHistoryKeyword: function(e) {
    const keyword = e.currentTarget.dataset.keyword;
    this.setData({
      keyword: keyword
    });
    this.onSearch();
  },

  // 关键词输入
  onKeywordInput: function(e) {
    this.setData({
      keyword: e.detail.value
    });
  },

  // 清除关键词
  clearKeyword: function() {
    this.setData({
      keyword: '',
      products: []
    });
  },

  // 搜索
  onSearch: function() {
    const keyword = this.data.keyword.trim();
    
    if (keyword) {
      this.saveSearchHistory(keyword);
      
      this.setData({
        currentPage: 1,
        products: [],
        hasMore: true
      });
      
      this.fetchProducts();
    }
  },

  // 选择分类
  selectCategory: function(e) {
    const category = e.currentTarget.dataset.category;
    
    this.setData({
      currentCategory: category,
      currentPage: 1,
      products: [],
      hasMore: true
    });
    
    this.fetchProducts();
  },

  // 选择地区
  selectRegion: function(e) {
    const region = e.currentTarget.dataset.region;
    
    this.setData({
      currentRegion: region,
      currentPage: 1,
      products: [],
      hasMore: true
    });
    
    this.fetchProducts();
  },

  // 选择排序方式
  selectSort: function(e) {
    const type = e.currentTarget.dataset.type;
    let priceOrder = this.data.priceOrder;
    
    if (type === 'price') {
      // 价格排序，切换升降序
      priceOrder = priceOrder === 'asc' ? 'desc' : 'asc';
    }
    
    this.setData({
      sortType: type,
      priceOrder: priceOrder,
      currentPage: 1,
      products: [],
      hasMore: true
    });
    
    this.fetchProducts();
  },

  // 显示筛选面板
  showFilterPanel: function() {
    this.setData({
      showFilter: true
    });
  },

  // 隐藏筛选面板
  hideFilterPanel: function() {
    this.setData({
      showFilter: false
    });
  },

  // 最低价输入
  onMinPriceInput: function(e) {
    this.setData({
      minPrice: e.detail.value
    });
  },

  // 最高价输入
  onMaxPriceInput: function(e) {
    this.setData({
      maxPrice: e.detail.value
    });
  },

  // 选择天数
  selectDays: function(e) {
    const days = e.currentTarget.dataset.days;
    
    // 如果已选中，则取消选中
    if (this.data.selectedDays === days) {
      this.setData({
        selectedDays: ''
      });
    } else {
      this.setData({
        selectedDays: days
      });
    }
  },

  // 切换主题
  toggleTheme: function(e) {
    const theme = e.currentTarget.dataset.theme;
    const selectedThemes = [...this.data.selectedThemes];
    
    const index = selectedThemes.indexOf(theme);
    
    if (index > -1) {
      // 如果已选中，则移除
      selectedThemes.splice(index, 1);
    } else {
      // 如果未选中，则添加
      selectedThemes.push(theme);
    }
    
    this.setData({
      selectedThemes: selectedThemes
    });
  },

  // 重置筛选
  resetFilter: function() {
    this.setData({
      minPrice: '',
      maxPrice: '',
      selectedDays: '',
      selectedThemes: []
    });
  },

  // 确认筛选
  confirmFilter: function() {
    this.hideFilterPanel();
    
    this.setData({
      currentPage: 1,
      products: [],
      hasMore: true
    });
    
    this.fetchProducts();
  },

  // 获取商品列表
  fetchProducts: function() {
    if (this.data.isLoading || !this.data.hasMore) return;
    
    this.setData({
      isLoading: true
    });
    
    // 构建查询参数
    const params = {
      page: this.data.currentPage,
      pageSize: this.data.pageSize,
      keyword: this.data.keyword,
      category: this.data.currentCategory !== 'all' ? this.data.currentCategory : '',
      region: this.data.currentRegion !== 'all' ? this.data.currentRegion : '',
      sortType: this.data.sortType,
      priceOrder: this.data.sortType === 'price' ? this.data.priceOrder : '',
      minPrice: this.data.minPrice,
      maxPrice: this.data.maxPrice,
      days: this.data.selectedDays,
      themes: this.data.selectedThemes
    };
    
    // 实际项目中应该从服务器获取数据
    // 这里使用模拟数据
    setTimeout(() => {
      // 模拟数据
      const mockProducts = [
        {
          id: 201,
          title: '美宿 | 西北寻秋 青甘环线7天6晚',
          regionName: '青甘',
          isHot: true,
          price: 8380,
          salesCount: 256,
          rating: 4.8,
          imageUrl: 'https://picsum.photos/id/1016/200/200'
        },
        {
          id: 202,
          title: '美宿 | 极致装达木 青海5天4晚',
          regionName: '青海',
          isHot: true,
          price: 6580,
          salesCount: 189,
          rating: 4.7,
          imageUrl: 'https://picsum.photos/id/1037/200/200'
        },
        {
          id: 203,
          title: '美宿 | 真容西北 青甘环线7天6晚',
          regionName: '青甘',
          isHot: false,
          price: 9380,
          salesCount: 145,
          rating: 4.9,
          imageUrl: 'https://picsum.photos/id/1041/200/200'
        },
        {
          id: 204,
          title: '美宿 | 蒙古秋末 青海6天5晚',
          regionName: '青海',
          isHot: false,
          price: 8380,
          salesCount: 132,
          rating: 4.6,
          imageUrl: 'https://picsum.photos/id/1019/200/200'
        },
        {
          id: 205,
          title: '轻奢 | 风马遗野 呼伦贝尔4晚5天',
          regionName: '内蒙',
          isHot: true,
          price: 7980,
          salesCount: 210,
          rating: 4.8,
          imageUrl: 'https://picsum.photos/id/1018/200/200'
        }
      ];
      
      // 模拟总数
      const totalCount = 28;
      
      // 模拟是否有更多
      const hasMore = this.data.currentPage * this.data.pageSize < totalCount;
      
      // 更新数据
      this.setData({
        products: [...this.data.products, ...mockProducts],
        totalCount: totalCount,
        hasMore: hasMore,
        isLoading: false,
        currentPage: this.data.currentPage + 1
      });
    }, 1000);
    
    // 实际项目中的云函数调用
    // wx.cloud.callFunction({
    //   name: 'getProducts',
    //   data: params,
    //   success: res => {
    //     if (res.result && res.result.data) {
    //       const { products, totalCount } = res.result.data;
    //       const hasMore = this.data.currentPage * this.data.pageSize < totalCount;
    //       
    //       this.setData({
    //         products: [...this.data.products, ...products],
    //         totalCount: totalCount,
    //         hasMore: hasMore,
    //         currentPage: this.data.currentPage + 1
    //       });
    //     }
    //   },
    //   fail: err => {
    //     console.error('获取商品列表失败', err);
    //   },
    //   complete: () => {
    //     this.setData({
    //       isLoading: false
    //     });
    //   }
    // });
  },

  // 加载更多
  loadMore: function() {
    this.fetchProducts();
  },

  // 跳转到详情页
  goToDetail: function(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/detail/detail?id=${id}`
    });
  },

  // 添加到购物车
  addToCart: function(e) {
    const id = e.currentTarget.dataset.id;
    
    // 检查登录状态
    if (!app.globalData.isLoggedIn) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    
    // 获取商品信息
    const product = this.data.products.find(item => item.id === id);
    
    if (product) {
      // 添加到购物车
      const cartItem = {
        id: Date.now(),
        productId: product.id,
        title: product.title,
        image: product.imageUrl,
        price: product.price,
        quantity: 1
      };
      
      let cart = wx.getStorageSync('cart') || [];
      cart.push(cartItem);
      wx.setStorageSync('cart', cart);
      
      wx.showToast({
        title: '已加入购物车',
        icon: 'success'
      });
    }
    
    // 实际项目中应该同步到服务器
    // wx.cloud.callFunction({
    //   name: 'addToCart',
    //   data: cartItem
    // });
  },

  onShareAppMessage: function() {
    return {
      title: '云途旅行 - 发现美好旅程',
      path: '/pages/search/search'
    };
  }
});
